<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="仓库编码" prop="postCode">
        <el-autocomplete v-model="state" clearable :fetch-suggestions="querySearchAsync" placeholder="请输入仓库编码"
                         @select="handleSelect"></el-autocomplete>
      </el-form-item>

      <el-form-item label="仓库名称" prop="postName">
        <el-autocomplete v-model="stateName" clearable :fetch-suggestions="querySearchAsyncName" placeholder="请输入仓库名称"
                         @select="handleSelectName"></el-autocomplete>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                   v-hasPermi="['system:post:add']">新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" :disabled="single" size="mini" @click="together"
                   v-hasPermi="['system:post:remove']">合并
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                   v-hasPermi="['system:post:export']">导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="postList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="仓库编号" align="center" prop="warehouseCode"/>
      <el-table-column label="仓库名称" align="center" prop="warehouseName"/>
      <el-table-column label="所属机构" align="center" prop="mechanismName"/>
      <el-table-column label="仓库地址" align="center" prop="address"/>

      <el-table-column label="仓库类型" align="center" prop="warehouseType">
        <template slot-scope="scope">
          <el-tag :key="scope.row.id" :type="scope.row.whTpyeName" effect="dark">
            {{ scope.row.whTpyeLabel }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag :key="scope.row.id" :type="scope.row.statusType" effect="dark">
            {{ scope.row.status }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="300" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['system:post:edit']">修改
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['system:post:remove']">删除
          </el-button>

          <el-button size="mini" type="text" icon="el-icon-delete" @click="goodsInfo(scope.row)"
                     v-hasPermi="['system:post:remove']">商品信息
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="batchList(scope.row)"
                     v-hasPermi="['system:post:remove']">批货清单
          </el-button>

        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>

    <!-- 添加或修改岗位对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="750px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="仓库名称" prop="warehouseName">
          <el-input v-model="form.warehouseName" placeholder="请输入仓库名称"/>
        </el-form-item>

        <el-form-item label="仓库类型" prop="warehouseType">
          <el-select v-model="warehouseType" placeholder="请选择仓库类型">
            <el-option v-for="item in options" :key="item.warehouseType" :label="item.label" :value="item.warehouseType"
                       :disabled="item.disabled">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="机构名称" prop="mechanismName">
          <el-select v-model="mechanismId" placeholder="请选择机构名称">
            <el-option v-for="item in mechanismList" :key="item.id" :label="item.mechanismName" :value="item.id"
                       :disabled="disabledOne">
            </el-option>
          </el-select>
        </el-form-item>

        <!-- ==============================================百度地图==================================================== -->
        <el-form-item label="仓库地址" prop="address">
          <!-- -----------------------------------地图一---------------------------------------  -->


          <el-autocomplete
            v-model="mapLocation.address"
            :fetch-suggestions="querySearch"
            placeholder="请输入详细地址"
            style="width: 100%"
            :trigger-on-focus="false"
            @select="handleSelect2"
          />

          <div style="margin: 5px">
            <baidu-map
              class="bm-view"
              :center="mapCenter"
              :zoom="mapZoom"
              :scroll-wheel-zoom="true"
              @ready="handlerBMap">
              <bm-geolocation @locationSuccess="locationSuccess" anchor="BMAP_ANCHOR_BOTTOM_RIGHT"
                              :showAddressBar="true" :autoLocation="true"></bm-geolocation>
            </baidu-map>
          </div>

          <!--            <baidu-map-->
          <!--            :center="center"-->
          <!--            :zoom="zoom"-->
          <!--            :scroll-wheel-zoom="true"-->
          <!--            @ready="handler"-->
          <!--            style="width: 100%; height:400px"-->
          <!--            >-->
          <!--   地图缩放   -->
          <!--              <bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-navigation>-->
          <!--   全景   -->
          <!--              <bm-panorama anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-panorama>-->
          <!--   城市定位   -->
          <!--              <bm-geolocation @locationSuccess="locationSuccess" anchor="BMAP_ANCHOR_BOTTOM_RIGHT" :showAddressBar="true" :autoLocation="true"></bm-geolocation>-->
          <!--   城市列表   -->
          <!--              <bm-city-list @changeAfter="changeAfter" anchor="BMAP_ANCHOR_TOP_LEFT"></bm-city-list>-->
          <!--            </baidu-map>-->

          <!--          <bm-local-search-->
          <!--            :keyword="keyword"-->
          <!--            @searchcomplete="onSearchComplete"-->
          <!--            :auto-viewport="true"-->
          <!--            :panel="false"-->
          <!--          ></bm-local-search>-->


        </el-form-item>
        <!-- ==============================================百度地图==================================================== -->

        <el-form-item label="仓库经纬度" prop="mapCode">
          <el-input v-model="form.mapCode" placeholder="请输入仓库经纬度"/>
        </el-form-item>

        <el-form-item label="每公里配送费" prop="deliveryFeeAveryKM">
          <el-input-number v-model="form.deliveryFeeAveryKM" placeholder="每公里配送费"/>
        </el-form-item>

        <el-form-item label="配送半径" prop="deliveryRadius">
          <el-input-number v-model="form.deliveryRadius" placeholder="配送半径"/>
        </el-form-item>

        <el-form-item label="电话" prop="tel">
          <el-input-number v-model="form.tel" placeholder="请输入电话"/>
        </el-form-item>

        <el-form-item label="起送数量" prop="startSendNum">
          <el-input-number v-model="form.startSendNum" placeholder="起送数量"/>
        </el-form-item>

        <el-form-item label="岗位状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.value">{{
                dict.label
              }}
            </el-radio>
          </el-radio-group>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--  =================================商品信息弹出框====================================  -->
    <el-dialog :title="title" :visible.sync="openGoods" width="900px" append-to-body>
      <el-table v-loading="loading" :data="postList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="仓库编号" align="center" prop="warehouseCode"/>
        <el-table-column label="仓库名称" align="center" prop="warehouseName"/>
        <el-table-column label="所属机构" align="center" prop="mechanismName"/>
        <el-table-column label="仓库地址" align="center" prop="address"/>

        <el-table-column label="仓库类型" align="center" prop="warehouseType">
          <template slot-scope="scope">
            <el-tag :key="scope.row.id" :type="scope.row.whTpyeName" effect="dark">
              {{ scope.row.whTpyeLabel }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="状态" align="center" prop="status">
          <template slot-scope="scope">
            <el-tag :key="scope.row.id" :type="scope.row.statusType" effect="dark">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center" width="300" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                       v-hasPermi="['system:post:edit']">修改
            </el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                       v-hasPermi="['system:post:remove']">删除
            </el-button>

            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                       v-hasPermi="['system:post:remove']">商品信息
            </el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                       v-hasPermi="['system:post:remove']">批货清单
            </el-button>

          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                  @pagination="getList"/>

    </el-dialog>
    <!--  =================================批货清单====================================  -->
    <el-dialog :title="title" :visible.sync="openBatch" width="900px" append-to-body>
      <el-table v-loading="loading" :data="postList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="仓库编号" align="center" prop="warehouseCode"/>
        <el-table-column label="仓库名称" align="center" prop="warehouseName"/>
        <el-table-column label="所属机构" align="center" prop="mechanismName"/>
        <el-table-column label="仓库地址" align="center" prop="address"/>

        <el-table-column label="仓库类型" align="center" prop="warehouseType">
          <template slot-scope="scope">
            <el-tag :key="scope.row.id" :type="scope.row.whTpyeName" effect="dark">
              {{ scope.row.whTpyeLabel }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="状态" align="center" prop="status">
          <template slot-scope="scope">
            <el-tag :key="scope.row.id" :type="scope.row.statusType" effect="dark">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center" width="300" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                       v-hasPermi="['system:post:edit']">修改
            </el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                       v-hasPermi="['system:post:remove']">删除
            </el-button>

            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                       v-hasPermi="['system:post:remove']">商品信息
            </el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                       v-hasPermi="['system:post:remove']">批货清单
            </el-button>

          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                  @pagination="getList"/>

    </el-dialog>

  </div>
</template>

<!-- 百度地图 -->
<script>
import BaiduMap from 'vue-baidu-map/components/map/Map.vue'
import {listWarehouse, getMechanismList, add, del, together2} from "@/api/zh/warehouse/post";

export default {
  name: "Post",
  dicts: ['sys_normal_disable'],

  components: {
    BaiduMap
  },
  data() {
    return {
      // 选中的数据集合
      list: [],
      openGoods: false,
      openBatch: false,
      //百度地图参数
      // center: {lng: 0, lat: 0},
      // zoom: 3,

      mapZoom: 15,
      mapCenter: {lng: 0, lat: 0},
      mapLocation: {
        address: undefined,
        coordinate: undefined
      },
      //百度地图参数

      mechanismId: '',
      disabledOne: false,
      addOrUpdate: 0, // 0:add, 1:update
      options: [{warehouseType: 1, label: '自营'}, {warehouseType: 2, label: '租赁',}],
      warehouseType: '',
      mechanismList: [],
      restaurants: [],
      restaurantsName: [],
      state: '',
      stateName: '',
      timeout: null,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 岗位表格数据
      postList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        warehouseCode: undefined,
        warehouseName: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        postName: [
          {required: true, message: "岗位名称不能为空", trigger: "blur"}
        ],
        postCode: [
          {required: true, message: "岗位编码不能为空", trigger: "blur"}
        ],
        postSort: [
          {required: true, message: "岗位顺序不能为空", trigger: "blur"}
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getMechanismList();
  },
  mounted() {
    // 百度地图

    // 百度地图
  },
  methods: {
    goodsInfo() {
      this.openGoods = true;
      console.log("商品信息管理");

    },
    batchList() {
      this.openBatch = true;
      console.log("商品信息管理");

    },
    together() {
      let code = '';
      for (let i = 0; i < this.list.length; i++) {
        code += this.list[i].warehouseCode + " "
      }
      if (confirm('是否确认合并编号为[ ' + code + ']的仓库？')){
        console.log("我确定了呀！")
        together2(this.list).then(response => {
          console.log(response)
          this.getList();
          this.loading = false;
          this.$modal.msgSuccess("合并成功");
        });

      }


    },
    // 百度地图
    // handler ({BMap, map}) {
    //   console.log(BMap, map)
    //   this.center.lng = 116.404
    //   this.center.lat = 39.915
    //   this.zoom = 15
    //
    // },
    handlerBMap({BMap, map}) {
      this.BMap = BMap
      this.map = map
      if (this.mapLocation.coordinate && this.mapLocation.coordinate.lng) {
        this.mapCenter.lng = this.mapLocation.coordinate.lng
        this.mapCenter.lat = this.mapLocation.coordinate.lat
        this.mapZoom = 15
        map.addOverlay(new this.BMap.Marker(this.mapLocation.coordinate))
      } else {
        this.mapCenter.lng = 113.271429
        this.mapCenter.lat = 23.135336
        this.mapZoom = 10
      }
    },
    querySearch(queryString, cb) {
      var that = this
      var myGeo = new this.BMap.Geocoder()
      myGeo.getPoint(queryString, function (point) {
        if (point) {
          that.mapLocation.coordinate = point
          that.makerCenter(point)
        } else {
          that.mapLocation.coordinate = null
        }
      }, this.locationCity)
      var options = {
        onSearchComplete: function (results) {
          if (local.getStatus() === 0) {
            // 判断状态是否正确
            var s = []
            for (var i = 0; i < results.getCurrentNumPois(); i++) {
              var x = results.getPoi(i)
              var item = {value: x.address + x.title, point: x.point}
              s.push(item)
              cb(s)
            }
          } else {
            cb()
          }
        }
      }
      var local = new this.BMap.LocalSearch(this.map, options)
      local.search(queryString)
    },
    handleSelect2(item) {
      var {point} = item
      this.mapLocation.coordinate = point
      this.makerCenter(point)
    },
    makerCenter(point) {
      if (this.map) {
        this.map.clearOverlays()
        this.map.addOverlay(new this.BMap.Marker(point))
        this.mapCenter.lng = point.lng
        this.mapCenter.lat = point.lat
        this.mapZoom = 15
      }
    },


    // 地图定位成功
    locationSuccess({point, AddressComponent, marker}) {
      console.log("定位成功", point, AddressComponent, marker)
      this.form.mapCode = point.lng + "," + point.lat;
    },
    // changeAfter(){
    //   console.log("列表选择完成后！")
    // },
    // 百度地图


    querySearchAsync(queryString, cb) {
      var restaurants = this.restaurants;
      var results = queryString ? restaurants.filter(this.createStateFilter(queryString)) : restaurants;

      clearTimeout(this.timeout);
      this.timeout = setTimeout(() => {
        cb(results);
      }, 1000 * Math.random());
    },
    createStateFilter(queryString) {
      return (state) => {
        return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    querySearchAsyncName(queryString, cb) {
      var restaurants = this.restaurantsName;
      var results = queryString ? restaurants.filter(this.createStateFilter(queryString)) : restaurants;

      clearTimeout(this.timeout);
      this.timeout = setTimeout(() => {
        cb(results);
      }, 1000 * Math.random());
    },
    handleSelect(item) {

    },
    handleSelectName(item) {

    },
    loadAll(list) {
      let arr = new Array()
      for (let i = 0; i < list.length; i++) {
        arr[i] = {"value": list[i].warehouseCode}
      }
      return arr;
    },
    loadAllName(list) {
      let arr = new Array()
      for (let i = 0; i < list.length; i++) {
        arr[i] = {"value": list[i].warehouseName}
      }
      return arr;
    },
    getMechanismList() {
      getMechanismList(this.queryParams).then(response => {
        this.mechanismList = response.rows;
        console.log(this.mechanismList.length, "机构id 机构名", this.mechanismList)
      });
    },
    /** 查询岗位列表 */
    getList() {
      this.loading = true;
      listWarehouse(this.queryParams).then(response => {
        this.postList = response.rows;
        this.total = response.total;
        this.loading = false;
        // 回显搜索按钮中的数据
        this.restaurants = this.loadAll(this.postList)
        this.restaurantsName = this.loadAllName(this.postList)
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        warehouseName: undefined,
        warehouseType: undefined,
        mechanismid: undefined,
        address: undefined,
        mapCode: undefined,
        deliveryFeeAveryKM: undefined,
        deliveryRadius: undefined,
        tel: undefined,
        startSendNum: undefined,

        status: "0",
        remark: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.queryParams.warehouseCode = this.state;
      this.queryParams.warehouseName = this.stateName;
      console.log(this.queryParams.warehouseCode, this.queryParams.warehouseName)
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.pageNum = 1;
      this.state = '';
      this.stateName = '';
      this.queryParams.warehouseCode = '';
      this.queryParams.warehouseName = '';
      this.getList();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.postId)
      this.single = selection.length < 2
      this.multiple = !selection.length
      this.list = selection;
      console.log("list", this.list)
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.addOrUpdate = 0;
      this.reset();
      this.warehouseType = '';
      this.mechanismId = '';
      this.open = true;
      this.title = "添加岗位";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.addOrUpdate = 1;
      this.reset();
      const postId = row.postId || this.ids
      // getPost(postId).then(response => {
      //   this.form = response.data;
      this.open = true;
      this.title = "修改岗位";
      // });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.addOrUpdate == 1) {
            console.log("this.form", this.form)
            // updatePost(this.form).then(response => {
            this.$modal.msgSuccess("修改成功");
            //   this.open = false;
            //   this.getList();
            // });
          } else {
            this.form.warehouseType = this.warehouseType;
            this.form.mechanismid = this.mechanismId;
            this.form.address = this.mapLocation.address
            console.log("this.form", this.form)
            add(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id;
      this.$modal.confirm('是否确认删除岗位编号为"' + id + '"的数据项？').then(function () {
        return del(id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('manage/warehouse/export', {
        ...this.queryParams
      }, `仓库信息_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style>
.bm-view {
  width: 100%;
  height: 500px;
}
</style>
